

const citys = require('./src/mock/mock.json')

const data = require('./src/mock/index')

const py = require('js-pinyin')

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target: "http://localhost:7002"
            }
        },

        before(app) {
            app.get('/api/changeCity', (req, res) => {
                //解构传递过来的城市名
                let { cityName } = req.query
                //筛选城市数据
                const data = citys.find(item => item.name.indexOf(cityName) !== -1)
                //通过筛选后数据的code值 ==> 继续筛选它的子级城市
                const area = citys.filter(item => item.parentCode === data.code)
                res.send({
                    code: 1,
                    area,  //子级城市
                    data //传递过来的城市数据
                })
            });


            app.get('/lists', (req, res) => {
                //处理数据 ==> 筛选市、县数据
                let list = data.filter(v => v.level > 1 && v.name !== '市辖区')
                //console.log(py.getFullChars(list[0].name));
                let cityObj = {}, //保存城市的对象
                    sortObj = {}
                list.map(v => {
                    //获取当前数据的name的拼音的首字母
                    let firstWord = py.getFullChars(v.name).slice(0, 1)

                    if (cityObj[firstWord]) {
                        cityObj[firstWord].push(v)
                    } else {
                        cityObj[firstWord] = [v]
                    }
                })
                //Object.keys: 返回由对象的键组成的新数组
                let wordList = Object.keys(cityObj).sort();
                wordList.map(v => {
                    sortObj[v] = cityObj[v]
                    return v;
                })

                res.send({
                    code: 1,
                    sortObj
                })
            })



        }

    }

}